package com.smart.reader.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.smart.reader.common.Page;
import com.smart.reader.exception.CustomException;
import com.smart.reader.mapper.ClassInfoMapper;
import com.smart.reader.model.bo.ClassInfoAddBo;
import com.smart.reader.model.bo.ClassInfoUpdateBo;
import com.smart.reader.model.po.ClassInfo;
import com.smart.reader.model.vo.ClassInfoVo;
import com.smart.reader.service.ClassInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.List;

@Service
public class ClassInfoServiceImpl extends ServiceImpl<ClassInfoMapper, ClassInfo> implements ClassInfoService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(ClassInfoAddBo classInfo) throws CustomException {
        ClassInfo info = BeanUtil.copyProperties(classInfo, ClassInfo.class);
        boolean save = this.save(info);
        if (!save) {
            throw new CustomException("班级数据添加失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public Page<ClassInfoVo> queryInfo(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClassInfoVo> classInfoVos = this.baseMapper.queryInfo();
        return new Page<>(pageNum, pageSize, classInfoVos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long id) throws CustomException {
        boolean remove = this.removeById(id);
        if (!remove) {
            throw new CustomException("班级数据删除失败");
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean edit(@Valid ClassInfoUpdateBo classInfo) throws CustomException {
        ClassInfo info = this.getById(classInfo.getId());
        if (ObjectUtil.isEmpty(info)) {
            throw new CustomException("班级数据不存在");
        }
        BeanUtil.copyProperties(classInfo, info);
        boolean update = this.updateById(info);
        if (!update) {
            throw new CustomException("班级数据修改失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public ClassInfoVo detail(Long id) {
        return this.baseMapper.detail(id);
    }
}
